//
//  YZMDiscoveryViewController.m
//  YZMicroStock
//
//  Created by apple on 16/12/6.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMDiscoveryViewController.h"
#import "YZMWebViewService.h"
#import "YZMSeparatorCell.h"
#import "YZClient+Account.h"
#import "YZGeneralResultModel.h"
#import "YZMAnnouncementModel.h"
#import "YZMAnnouncementCell.h"
#import "YZMAnnouncementDetailCell.h"
#import "YZMAnnouncementListModel.h"


static NSString *const YZMDiscoveryCellId = @"YZMSeparatorCellId";
static NSString *const YZMAnnCellId = @"YZMAnnCellId";
static NSString *const YZMAnnouncementDetailCellId = @"YZMAnnouncementDetailCellId";

@interface YZMDiscoveryViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) NSArray *datasource;
@property (nonatomic, strong) UITableView *annTableView;
@property (nonatomic, strong) NSMutableArray *annArr;
@property (nonatomic, strong) NSIndexPath *insertIndexPath;
@property (nonatomic, strong) NSIndexPath *deleteIndexPath;
@property (nonatomic, strong) UIView *topView;

@end

@implementation YZMDiscoveryViewController

- (instancetype)init{
    
    self = [super init];
    if (self) {
        
        self.title = YZMSWitchOn ? @"发现" : @"通知";
        _annArr = [NSMutableArray array];
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self createObj];
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    if (YZMSWitchOn) {
        [self fetchAnnouncementList];
    }
}

//请求公告列表
- (void)fetchAnnouncementList {
    
    [YZClient fetchNoticeListSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            YZMAnnouncementModel *model = topModel.data;
            if (model.items.count > 0) {
                
                [_annArr removeAllObjects];
                [_annArr addObjectsFromArray:model.items];
                if (!_insertIndexPath) {
                    
                    _insertIndexPath = [NSIndexPath indexPathForRow:1 inSection:0];
                }
                [_annTableView reloadData];
            }
        }
    } failure:^(NSError *error) {
        
        
    }];
}

-(void)createObj{
    
    WS(ws)
    
    
    [self createTopView];
    _annTableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) style:UITableViewStylePlain];
    _annTableView.backgroundColor=[YZMAppStyle appBackgroundColor];
    [_annTableView registerClass:[YZMAnnouncementCell class] forCellReuseIdentifier:YZMAnnCellId];
    [_annTableView registerClass:[YZMAnnouncementDetailCell class] forCellReuseIdentifier:YZMAnnouncementDetailCellId];
    _annTableView.delegate=self;
    _annTableView.dataSource=self;
    _annTableView.bounces=NO;
    _annTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    _annTableView.estimatedRowHeight = 46;
    _annTableView.rowHeight = UITableViewAutomaticDimension;
    [self.view addSubview:_annTableView];
    [_annTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(ws.topView.mas_bottom);
        make.bottom.left.right.equalTo(ws.view);
    }];
    
    if (!YZMSWitchOn) {
        
        NSString *path = [[NSBundle mainBundle] pathForResource:@"discovery" ofType:@"json"];
        NSData *data = [[NSData alloc] initWithContentsOfFile:path];
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        _annArr = [NSMutableArray array];
        NSInteger i = -1;
        for (NSDictionary *dic in arr) {
            i++;
            YZMAnnouncementListModel *model = [MTLJSONAdapter modelOfClass:[YZMAnnouncementListModel class] fromJSONDictionary:dic error:nil];
            NSCalendar *calendar = [NSCalendar currentCalendar];
            NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |NSCalendarUnitHour | NSCalendarUnitMinute;
            NSDateComponents *compons = [calendar components:unit fromDate:[NSDate date]];
            switch (i) {
                case 0:
                    compons.day = 4;
                    compons.hour = 10;
                    compons.minute = 36;
                    break;
                case 1:
                    compons.day = 7;
                    compons.hour = 13;
                    compons.minute = 24;
                    break;
                case 2:
                    compons.day = 9;
                    compons.hour = 15;
                    compons.minute = 05;
                    break;
                default:
                    break;
            }
            
            NSDate *date = [calendar dateFromComponents:compons];
            model.releaseTime = date;
            [_annArr addObject:model];
        }
    }
}

//顶部视图
-(void)createTopView{
    
    WS(ws)
    
    self.topView = [UIView new];
    [self.view addSubview:self.topView];
    [_topView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(ws.view);
        if (YZMSWitchOn) {
            make.height.mas_equalTo(104 + 35);
        }else{
            make.height.mas_equalTo(35);
        }
    }];
    
    UIView *backView = [UIView new];
    [self.topView addSubview:backView];
    backView.backgroundColor = [YZMAppStyle colorForMain];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(76);
        make.top.equalTo(ws.topView).offset(14);
        make.left.right.equalTo(ws.topView);
    }];
    
    
    NSArray *textArray = [NSArray arrayWithObjects:@"活动中心", @"推广赚钱", @"佣金收入榜",nil];
    NSArray *imageViewArray = [NSArray arrayWithObjects:@"icon_discovery_activity", @"icon_discovery_spread", @"icon_discovery_commision", nil];
//#ifdef YZMicroStock
    
    for (int i = 0; i<textArray.count; i++) {
        
        UIView *view = [UIView new];
        [backView addSubview:view];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.bottom.equalTo(backView);
            make.width.mas_equalTo(ScreenWidth/textArray.count);
            make.left.equalTo(backView).offset(ScreenWidth/textArray.count*i);
        }];
        
        UIImageView *imageView = [UIImageView new];
        [view addSubview:imageView];
        [imageView setImage:[UIImage imageNamed:imageViewArray[i]]];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.width.height.mas_equalTo(32);
            make.centerX.equalTo(view);
            make.top.equalTo(view).offset(12);
        }];
        
        UILabel *label = [YZMAppStyle labelWithSmallWhite];
        [view addSubview:label];
        label.text = textArray[i];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.centerX.equalTo(imageView);
            make.top.equalTo(imageView.mas_bottom).offset(9);
        }];
        
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [view addSubview:clickBtn];
        clickBtn.backgroundColor = [UIColor clearColor];
        clickBtn.tag = 100 + i;
        [clickBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.bottom.left.right.equalTo(view);
        }];
        [clickBtn addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    
//#else
//    textArray = [NSArray arrayWithObjects:@"每日盈利榜",nil];
//    imageViewArray = [NSArray arrayWithObjects:@"icon_discovery_daygains", nil];
//    
//    for (int i = 0; i<textArray.count; i++) {
//        
//        UIView *view = [UIView new];
//        [backView addSubview:view];
//        [view mas_makeConstraints:^(MASConstraintMaker *make) {
//            
//            make.top.bottom.equalTo(backView);
//            make.width.mas_equalTo(ScreenWidth/4);
//            make.left.equalTo(backView).offset(ScreenWidth/4*i);
//        }];
//        
//        UIImageView *imageView = [UIImageView new];
//        [view addSubview:imageView];
//        [imageView setImage:[UIImage imageNamed:imageViewArray[i]]];
//        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
//            
//            make.width.height.mas_equalTo(32);
//            make.centerX.equalTo(view);
//            make.top.equalTo(view).offset(12);
//        }];
//        
//        UILabel *label = [YZMAppStyle labelWithSmallWhite];
//        [view addSubview:label];
//        label.text = textArray[i];
//        [label mas_makeConstraints:^(MASConstraintMaker *make) {
//            
//            make.centerX.equalTo(imageView);
//            make.top.equalTo(imageView.mas_bottom).offset(9);
//        }];
//        
//        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [view addSubview:clickBtn];
//        clickBtn.backgroundColor = [UIColor clearColor];
//        clickBtn.tag = 100 + i;
//        [clickBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            
//            make.top.bottom.left.right.equalTo(view);
//        }];
//        [clickBtn addTarget:self action:@selector(clickActionAgent:) forControlEvents:UIControlEventTouchUpInside];
//    }
//#endif
    
    
    UIView *lastView = [UIView new];
    [self.view addSubview:lastView];
    lastView.backgroundColor = [YZMAppStyle colorForMain];
    [lastView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(35);
        make.bottom.left.right.equalTo(ws.topView);
    }];
    
    UILabel *textLabel = [YZMAppStyle labelWithMediumWhite];
    textLabel.text = @"公告信息";
    [lastView addSubview:textLabel];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(lastView).offset(20);
        make.centerY.equalTo(lastView);
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _annArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (self.insertIndexPath) {
        
        if (section == self.insertIndexPath.section) {
            
            return 2;
        }
    }
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YZMAnnouncementListModel *modelDic = _annArr[indexPath.section];
    if (indexPath.row == 0) {
        //公告信息表头
        YZMAnnouncementCell *cell=[tableView dequeueReusableCellWithIdentifier:YZMAnnCellId forIndexPath:indexPath];
        cell.model = modelDic;
        cell.bottomLine.hidden = YES;
        if (indexPath.section == _annArr.count-1) {
            cell.bottomLine.hidden = NO;
        }
        if (self.insertIndexPath.section == indexPath.section && self.insertIndexPath) {
            
            cell.arrowImage.hidden = YES;
            cell.bottomLine.hidden = YES;
        }
        else {
            cell.arrowImage.hidden = NO;
        }
        
        return cell;
    } else {
        //公告信息内容
        YZMAnnouncementDetailCell *cell=[tableView dequeueReusableCellWithIdentifier:YZMAnnouncementDetailCellId forIndexPath:indexPath];
        cell.model = modelDic;
        cell.bottomLine.hidden = YES;
        if (indexPath.section == _annArr.count-1) {
            
            cell.bottomLine.hidden = NO;
        }
        
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (!self.insertIndexPath) {
        
        self.insertIndexPath = [NSIndexPath indexPathForRow:1 inSection:indexPath.section];
        //插入公告内容
        [self insertOrDeleteCell:YES withIndexPath:self.insertIndexPath];
        //刷新指定cell
        [self refreshCell:[NSIndexPath indexPathForRow:0 inSection:indexPath.section]];
        } else {
            
            if (indexPath.section == self.insertIndexPath.section) {
                
                self.deleteIndexPath = self.insertIndexPath;
                self.insertIndexPath = nil;
                //删除上一次选择的公告内容
                [self insertOrDeleteCell:NO withIndexPath:self.deleteIndexPath];
                //刷新指定cell
                [self refreshCell:[NSIndexPath indexPathForRow:0 inSection:self.deleteIndexPath.section]];
                self.deleteIndexPath = nil;
            } else {
            
                self.deleteIndexPath = self.insertIndexPath;
                self.insertIndexPath = nil;
                //删除上一次选择的公告内容
                [self insertOrDeleteCell:NO withIndexPath:self.deleteIndexPath];
                //刷新指定cell
                [self refreshCell:[NSIndexPath indexPathForRow:0 inSection:self.deleteIndexPath.section]];
                self.deleteIndexPath = nil;
                self.insertIndexPath = [NSIndexPath indexPathForRow:1 inSection:indexPath.section];
                //插入公告内容
                [self insertOrDeleteCell:YES withIndexPath:self.insertIndexPath];
                //刷新指定cell
                [self refreshCell:[NSIndexPath indexPathForRow:0 inSection:self.insertIndexPath.section]];
        }
    }
}

//顶部视图的相关点击方法
-(void)clickAction:(UIButton *)sender{
    
    switch (sender.tag) {
            
        case 100:
            [YZMCMInstance pushViewControllerWithName:@"activity" andParams:nil];
            break;
            
        case 101:
            [YZMCMInstance pushViewControllerWithName:@"AboutSpread" andParams:nil];
            break;
            
//        case 102:
//            [YZMCMInstance pushViewControllerWithName:@"daygain" andParams:nil];
//            break;
            
        case 102:
            [YZMCMInstance pushViewControllerWithName:@"commission" andParams:nil];
            break;
            
        default:
            break;
    }
}

-(void)clickActionAgent:(UIButton *)sender{
    
    [YZMCMInstance pushViewControllerWithName:@"daygain" andParams:nil];
}

//刷新指定cell
- (void)refreshCell:(NSIndexPath *)index {
    
    [_annTableView reloadRowsAtIndexPaths:@[index] withRowAnimation:UITableViewRowAnimationNone];
}

//插入或删除指定cell
- (void)insertOrDeleteCell:(BOOL)isInsert withIndexPath:(NSIndexPath *)indexPath {
    
    if (isInsert) {
        
        [_annTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else {
        
        [_annTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
